<template>
  <n-drawer v-model:show="open" :width="700" placement="right">
    <n-drawer-content title="设置" closable>
      <NCollapse display-directive="show" arrow-placement="right" :default-expanded-names="['gitlibConfig']">
        <NCollapseItem title="Gitlib 配置" name="gitlibConfig">
          <n-form
            label-placement="left"
            :model="gitlibConfig"
            label-width="auto"
            size="small">
            <n-form-item label="服务地址" path="server" :rule="{ required: true, message: '请输入服务地址', trigger: 'blur' }">
              <n-input v-model:value="gitlibConfig.server" clearable placeholder="请输入服务地址" />
            </n-form-item>
            <n-form-item label="访问令牌" path="token" :rule="{ required: true, message: '请输入访问令牌', trigger: 'blur' }">
              <n-input v-model:value="gitlibConfig.token" clearable placeholder="请输入访问令牌" />
            </n-form-item>
            <!-- <n-form-item label="是否备份"  path="isBak">
              <n-switch  v-model:value="fileConfig.isBak" size="small" />
            </n-form-item>
            <n-form-item v-show="fileConfig.isBak" label="清理文件备份路径" path="bakPath">
              <n-input-group>
                <n-input v-model:value="fileConfig.bakPath" :disabled="systemConfig.isSecurity" clearable placeholder="请选择清理文件的备份路径" />
                <n-button @click="handleFileDialog(val => fileConfig.bakPath = val)">选择</n-button>
              </n-input-group>
            </n-form-item>
            <n-form-item label="可处理文件类型" path="bakPath">
              <n-select v-model:value="fileConfig.types" :disabled="systemConfig.isSecurity" multiple clearable :options="typeOptions" placeholder="请选择可处理文件类型" />
            </n-form-item>
            <n-form-item label="保留文件保存路径" path="movePath">
              <n-input-group>
                <n-input v-model:value="fileConfig.movePath" :disabled="systemConfig.isSecurity" clearable placeholder="请选择保留文件保存路径" />
                <n-button @click="handleFileDialog(val => fileConfig.movePath = val)">选择</n-button>
              </n-input-group>
            </n-form-item> -->
          </n-form>
        </NCollapseItem>
      </NCollapse>
      <n-button type="info" @click="checkUser">检查</n-button>
      <!-- <n-button @click="getProjects">项目2</n-button>
      <n-button @click="getProjectCommits(867)">commits2</n-button> -->
      <n-button type="primary" @click="getCurrentUserCommits">开始等待吧</n-button>
    </n-drawer-content>
  </n-drawer>
</template>

<script setup lang="ts">
import { useConfigStore } from '@/store/config'

const configStore = useConfigStore()

const { getGitLabApi: api } = toRefs(configStore)

const checkUser = async () => {
  try {
    const currentUser = await api.value.Users.showCurrentUser()
    window.$message.info(`当前用户信息为 ${currentUser.name} ${currentUser.email}`)
  } catch (err) {
    const message = err instanceof Error ? err.message : err
    window.$message.error(`检查失败！${message}`)
  }
}

// /**
//  * 获取项目信息
//  */
// const getProjects = async () => {
//   const projects = await api.value.Projects.all({ perPage: '100' })
//   console.log(projects)
// }

// const getProjectCommits = async (projectId: string | number) => {
//   const commits = await api.value.Commits.all(projectId, { perPage: '100' })
//   console.log(commits)

//   const commit = await api.value.Commits.show(projectId, commits[0].id, { stats: true })
//   console.log(commit)
// }

const getCurrentUserCommits = async () => {
  // 查询当前用户
  const currentUser = await api.value.Users.showCurrentUser()
  const startDate = new Date('2024-01-01').toISOString()
  console.log(currentUser)
    // 查项目
    const projects = await api.value.Projects.all({ perPage: '100' })
  // 查项目提交
  let projectCommits = await Promise.all(projects.map(async project => {
    let commitsResult = await api.value.Commits.all(project.id, { perPage: '100', since: startDate })
    commitsResult = commitsResult.filter(commit => commit.author_name === currentUser.name && commit.committed_date && commit?.committed_date >= startDate)

    if (commitsResult.length == 0) {
      return []
    }
    // 查询详情

    return await Promise.all(commitsResult.map(async commit => {
      const commitInfo = await api.value.Commits.show(project.id, commit.id)
      return {
        projectId: project.id,
        projectName: project.name,
        commitId: commitInfo.id,
        message: commitInfo.message,
        authored_date: commitInfo.authored_date,
        author_name: commitInfo.author_name,
        ...commitInfo.stats,
      }
    }))
  }))
  // 过滤本人无提交项目
  const result = projectCommits.flatMap(item => item)
  console.log(result)
  return result
}

</script>

<style lang="css">
.icon-lable {
  line-height: 1;
}
.icon:hover{
  color: var(--icon-color-hover);
}
</style>
